package com.example.shiwu;

import static com.example.shiwu.util.FileDownUtil.createDownLoadFile;
import static com.example.shiwu.util.FileDownUtil.createHiddenFolderOnSdCard;
import static com.example.shiwu.util.FileDownUtil.createShiwuFile;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.example.shiwu.db.dao.AlarmDao;
import com.example.shiwu.db.dao.AlarmVoDao;
import com.example.shiwu.db.dao.ArrangeDao;
import com.example.shiwu.db.dao.BoxEightDao;
import com.example.shiwu.db.dao.BoxElectrodeRoDao;
import com.example.shiwu.db.dao.BoxFiveDao;
import com.example.shiwu.db.dao.BoxFourDao;
import com.example.shiwu.db.dao.BoxNineDao;
import com.example.shiwu.db.dao.BoxOneDao;
import com.example.shiwu.db.dao.BoxSevenDao;
import com.example.shiwu.db.dao.BoxSixDao;
import com.example.shiwu.db.dao.BoxTenDao;
import com.example.shiwu.db.dao.BoxThreeDao;
import com.example.shiwu.db.dao.BoxTwoDao;
import com.example.shiwu.db.dao.DeviceDao;
import com.example.shiwu.db.dao.ItemsDao;
import com.example.shiwu.db.dao.PhotoDao;
import com.example.shiwu.db.dao.ReceiveDao;
import com.example.shiwu.db.dao.ReceiveVolEleDao;
import com.example.shiwu.db.dao.SendsDao;
import com.example.shiwu.db.dao.UserDao;
import com.example.shiwu.db.dao.base.BaseDaoFactory;
import com.example.shiwu.db.model.Alarm;
import com.example.shiwu.db.model.Arrange;
import com.example.shiwu.db.model.BoxEight;
import com.example.shiwu.db.model.BoxElectrodeRo;
import com.example.shiwu.db.model.BoxFive;
import com.example.shiwu.db.model.BoxFour;
import com.example.shiwu.db.model.BoxNine;
import com.example.shiwu.db.model.BoxOne;
import com.example.shiwu.db.model.BoxSeven;
import com.example.shiwu.db.model.BoxSix;
import com.example.shiwu.db.model.BoxTen;
import com.example.shiwu.db.model.BoxThree;
import com.example.shiwu.db.model.BoxTwo;
import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.model.Photo;
import com.example.shiwu.db.model.Receive;
import com.example.shiwu.db.model.ReceiveVolEle;
import com.example.shiwu.db.model.Sends;
import com.example.shiwu.db.model.User;
import com.example.shiwu.db.vo.AlarmVo;
import com.example.shiwu.service.UserService;
import com.example.shiwu.util.EncryptedFolderHelper;

import org.json.JSONException;

import java.io.FileNotFoundException;
import java.util.ArrayList;

public class SplashActivity extends AppCompatActivity {

    private static final int SPLASH_DURATION = 2000; // 启动页展示的时间，单位为毫秒
    private UserDao<User> userDao;
    private ItemsDao<Items> itemsDao;
    private DeviceDao<Device> deviceDao;
    private SendsDao<Device> sendsDao;
    private AlarmDao<Device> alarmDao;
    private AlarmVoDao<Device> alarmVoDao;
    private PhotoDao<Photo> photoDao;
    private ReceiveDao<Photo> receiveDao;
    private ArrangeDao<Photo> arrangeDao;
    private BoxOneDao<BoxOne> boxOneDao;
    private BoxTwoDao<BoxTwo> boxTwoDao;
    private BoxThreeDao<BoxThree> boxThreeDao;
    private BoxFourDao<BoxFour> boxFourDao;
    private BoxFiveDao<BoxFive> boxFiveDao;
    private BoxSixDao<BoxSix> boxSixDao;
    private BoxSevenDao<BoxSeven> boxSevenDao;
    private BoxEightDao<BoxEight> boxEightDao;
    private BoxNineDao<BoxNine> boxNineDao;
    private BoxTenDao<BoxTen> boxTenDao;
    private BoxElectrodeRoDao<BoxElectrodeRo> boxElectrodeRoDao;
    private ReceiveVolEleDao<ReceiveVolEle> receiveVolAndEleDao;

    private ArrayList<User> listUser = new ArrayList<>();
    private UserService userService;

    private ImageView lodding;
    private Python py;
    private PyObject pyobj, pyobj1, pyobj2, pyobj3, pyplot;
    private Context myContext;

    private static final int PERMISSION_REQUEST_CODE = 100;
    private static final String[] REQUIRED_PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    public SplashActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myContext = this;
        setContentView(R.layout.activity_splash);
        setContentView(R.layout.activity_splash);

        // 检查并请求权限
        if (checkRequiredPermissions()) {
            // 权限已授予，直接进入主页
            navigateToMainActivity();
        } else {
            // 请求权限
            ActivityCompat.requestPermissions(
                    this,
                    REQUIRED_PERMISSIONS,
                    PERMISSION_REQUEST_CODE
            );
        }


    }

    // 检查是否所有必需权限都已授予
    private boolean checkRequiredPermissions() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true; // Android 6.0以下无需运行时权限
        }
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(
                    this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(
            int requestCode,
            @NonNull String[] permissions,
            @NonNull int[] grantResults
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，进入主页
                navigateToMainActivity();
            } else {
                // 权限被拒绝，提示用户并退出应用
                Toast.makeText(this, "需要文件读取权限才能继续",
                        Toast.LENGTH_SHORT).show();
                finish(); // 关闭启动页
            }
        }
    }

    // 跳转到主页
    private void navigateToMainActivity() {
        createTable();
        lodding = findViewById(R.id.imageViewSplash);
        // 在合适的地方调用以下代码
        Glide.with(myContext)
                .asGif()
                .load(R.drawable.loading)
                .into(lodding);
        userService = new UserService();

        boolean bl = userService.register("swAdmin", "swAdmin123", 0,1);//默认注册admin密码123456
        boolean bl1 = userService.register("user", "123456", 0,0);//默认注册admin密码123456
        Log.i("启动页", "注册成功");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();

            }
        }, SPLASH_DURATION);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    initPython(myContext);
                    //createDownLoadFile(myContext);
                    Boolean bo = createShiwuFile();

                    Log.e("shiwu","shiwu创建成功");
//                    pickDirectory();
                    //createHiddenFolderOnSdCard(myContext);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

    }

    private void initPython(Context myContext) throws JSONException, InterruptedException {
        //初始化python环境
        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(myContext));
        }

        py = Python.getInstance();
        //调用hello_python.py里面的plot函式
        pyobj = py.getModule("plotmy");
        pyobj1 = py.getModule("Send_Param");
        pyobj2 = py.getModule("ERT_UI_ARRAY");
        pyobj3 = py.getModule("SECTION_ARRAY");


    }

//    public Boolean requestPermission(
//            Activity activity) {
//
//        createTable();
//        Boolean bool = false;
//        if (android.os.Build.VERSION.SDK_INT > 9) {
//            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//            StrictMode.setThreadPolicy(policy);
//        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
//                !Environment.isExternalStorageManager()) {
//
//            Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
//            startActivity(intent);
//        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ActivityCompat.checkSelfPermission(activity,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(activity, new String[]{
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE
//            }, 1);
//            bool = true;
//        }
//
//        return bool;
//    }

    private void createTable() {
        userDao = BaseDaoFactory.getInstance().createBaseDao(UserDao.class, User.class);
        itemsDao = BaseDaoFactory.getInstance().createBaseDao(ItemsDao.class, Items.class);
        //photoDao = BaseDaoFactory.getInstance().createBaseDao(PhotoDao.class, Photo.class);
        deviceDao = BaseDaoFactory.getInstance().createBaseDao(DeviceDao.class, Device.class);
        sendsDao = BaseDaoFactory.getInstance().createBaseDao(SendsDao.class, Sends.class);
        receiveDao = BaseDaoFactory.getInstance().createBaseDao(ReceiveDao.class, Receive.class);
        arrangeDao = BaseDaoFactory.getInstance().createBaseDao(ArrangeDao.class, Arrange.class);
        alarmDao = BaseDaoFactory.getInstance().createBaseDao(AlarmDao.class, Alarm.class);
        alarmVoDao = BaseDaoFactory.getInstance().createBaseDao(AlarmVoDao.class, AlarmVo.class);
        receiveVolAndEleDao = BaseDaoFactory.getInstance().createBaseDao(ReceiveVolEleDao.class, ReceiveVolEle.class);
        boxOneDao = BaseDaoFactory.getInstance().createBaseDao(BoxOneDao.class, BoxOne.class);
        boxTwoDao = BaseDaoFactory.getInstance().createBaseDao(BoxTwoDao.class, BoxTwo.class);
        boxThreeDao = BaseDaoFactory.getInstance().createBaseDao(BoxThreeDao.class, BoxThree.class);
        boxFourDao = BaseDaoFactory.getInstance().createBaseDao(BoxFourDao.class, BoxFour.class);
        boxFiveDao = BaseDaoFactory.getInstance().createBaseDao(BoxFiveDao.class, BoxFive.class);
        boxSixDao = BaseDaoFactory.getInstance().createBaseDao(BoxSixDao.class, BoxSix.class);
        boxSevenDao = BaseDaoFactory.getInstance().createBaseDao(BoxSevenDao.class, BoxSeven.class);
        boxEightDao = BaseDaoFactory.getInstance().createBaseDao(BoxEightDao.class, BoxEight.class);
        boxNineDao = BaseDaoFactory.getInstance().createBaseDao(BoxNineDao.class, BoxNine.class);
        boxTenDao = BaseDaoFactory.getInstance().createBaseDao(BoxTenDao.class, BoxTen.class);
        boxElectrodeRoDao = BaseDaoFactory.getInstance().createBaseDao(BoxElectrodeRoDao.class, BoxElectrodeRo.class);
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        createTable();
//    }

    // 1. 定义请求码
    private static final int REQUEST_CODE_PICK_DIR = 100;

    // 2. 触发目录选择
    public void pickDirectory() {
//        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
//        // 可选：指定初始目录（如Downloads），部分设备支持
//        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
//        startActivityForResult(intent, REQUEST_CODE_PICK_DIR);
        // 在Activity或Fragment中使用
        EncryptedFolderHelper helper = new EncryptedFolderHelper(this);
        Object folder = helper.createEncryptedFolder("MyEncryptedFolder");

        if (folder != null) {
            if (folder instanceof Uri) {
                // Android 10及以上，使用Uri操作
                Uri folderUri = (Uri) folder;
                // 可以使用这个Uri来创建加密文件
            } else if (folder instanceof String) {
                // Android 10以下，使用路径操作
                String folderPath = (String) folder;
                // 可以使用这个路径来创建加密文件
            }
        }
    }

    // 3. 处理返回结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_DIR && resultCode == RESULT_OK) {
            // 获取用户选择的目录Uri（treeUri）
            Uri treeUri = data.getData();
            if (treeUri != null) {
                // 4. 获取持久化权限（关键：否则应用重启后权限失效）
                getContentResolver().takePersistableUriPermission(
                        treeUri,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                );

                // 5. 保存treeUri（例如存入SharedPreferences）
                saveTreeUri(treeUri.toString());

                // 后续可使用treeUri操作目录（如创建文件/文件夹）
                Log.d("TreeUri", "获取成功：" + treeUri);
            }
        }
    }

    // 保存treeUri到SharedPreferences
    private void saveTreeUri(String uriStr) {
        String strUrl = "content://com.android.externalstorage.documents/tree/primary%3ADownload%2Fshiwu";
        SharedPreferences sp = getSharedPreferences("app_prefs", MODE_PRIVATE);
        sp.edit().putString("selected_tree_uri", uriStr).apply();
    }
}
